package com.mysql.test;

import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;

public class ConnectionPool {

    private static LinkedList<Connection> connectionList;

    private static String driver ="com.mysql.jdbc.Driver";
    private static String url="jdbc:mysql://127.0.0.1:3306/mydatabase?useUnicode=true&characterEncoding=utf-8";
    private static String user="root";
    private static String password="610527";
    private static int connectionNum = 3;

    /**
     * 初始化
     */
    static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        connectionList = new LinkedList<>();
        for (int i = 0; i < connectionNum; i++) {
            connectionList.add(initConnection());
        }
        System.out.println(connectionList.size());
    }

    /**
     * 连接
     * @return
     */
    private static Connection initConnection(){
        try {
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 对外提供获取连接的
     * @return
     */
    public Connection getConnection(){
        if(connectionList.isEmpty()){
            System.out.println("获取成功：连接已使用完,创建新的连接"+connectionList.size());
             return this.initConnection();
        }
        System.out.println("获取成功：从连接池中获取连接"+connectionList.size());
        return connectionList.remove();
    }

    /**
     * 对外提供关闭连接
     * @param connection
     */
    public void closeConnection(Connection connection){
        if(connectionList.size() < connectionNum){
            System.out.println("关闭成功：实际并没有关闭，而是回到连接池中"+connectionList.size());
            connectionList.add(connection);
        }else {
            try {
                System.out.println("关闭成功：连接池已满，关闭此连接" +connectionList.size() );
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void testConnectionPool(){
        getConnection();
        getConnection();
        getConnection();
        getConnection();
        getConnection();
        Connection connection = getConnection();
        closeConnection(connection);
    }
}
